<?php
namespace app\controller;

use think\facade\View;
use think\facade\Db;

class Index
{
    public function index()
    {
        View::assign('name', '欢迎使用 ThinkPHP 6！');
        return View::fetch('index');
    }

    public function api()
    { 
        return View::fetch('api');
    }

    public function getlogin()
    {  
        $token = bin2hex(random_bytes(32));  
        $postData = json_decode(file_get_contents('php://input'), true); 
        if(trim($postData['username']) == 'user123' && trim($postData['password']) == 'admin123'){
            $this->ajaxReturn(['status' => 'success', 'username' =>'user123','password' => 'admin123'], 'json'); 
        } else {
            $this->ajaxReturn(['status' => 'error', 'data' =>[],'token' => ''], 'json'); 
        } 
    }

    public function getAllIps()
    {
        $batchSize = 1000;

        // 使用Db类进行数据查询
        $existingIps = Db::table('AD_dns_ipRuleServer_api')
            ->field('server_addr')
            ->limit($batchSize)
            ->select()
            ->toArray();

        // 获取数据总量
        $total = Db::table('AD_dns_ipRuleServer_api')->count();

        // 分批次查询
        $totalBatches = ceil($total / $batchSize);
        for ($i = 0; $i < $totalBatches; $i++) {
            $offset = $i * $batchSize;
            $batchIps = Db::table('AD_dns_ipRuleServer_api')
                ->field('server_addr')
                ->limit($offset, $batchSize)
                ->select()
                ->toArray();
        }
    }

    public function getIpData()
    {  
        // 使用Db类获取 IP 数据
        $ipData = Db::table('AD_dns_ipRuleServer_api')
            ->order('is_main_addr', 'desc')
            ->order('update_time', 'desc')
            ->field('id, server_addr, is_main_addr, server_id, create_time, update_time, rent_time, status')
            ->select()
            ->toArray(); 
        
        $ruleIpCount = [];
        foreach ($ipData as $item) {
            $server_id = $item['server_id'];
            if (!isset($ruleIpCount[$server_id])) {
                $ruleIpCount[$server_id] = 0;
            }
            $ruleIpCount[$server_id]++;
        }

        $groupedData = [];
        $ruleServerCount = [];

        foreach ($ipData as &$item) {
            $room = $item['server_id'];
            $item['rule_name'] = $room;
            $groupId = $item['server_id'];

            if (!isset($groupedData[$room])) {
                $groupedData[$room] = [];
            }

            if (!isset($groupedData[$room][$groupId])) {
                $groupedData[$room][$groupId] = [
                    'ruleName' => $room,
                    'group' => $groupId,
                    'time' => $item['rent_time'],
                    'ips' => [],
                    'count' => 0,
                ];
            }

            $groupedData[$room][$groupId]['ips'][] = [
                'ip' => $item['server_addr'],
                'is_main_addr' => $item['is_main_addr'],
                'status' => $item['status']
            ];
            $groupedData[$room][$groupId]['count'] = count($groupedData[$room][$groupId]['ips']);
            $ruleServerCount[$room] = count($groupedData[$room]);
        }

        arsort($ruleIpCount);
        arsort($ruleServerCount);

        $export = request()->get('export', 0, 'intval');
        if ($export) {
            $this->exportDataToExcelOne($groupedData);
        } else {
            return json([
                'status' => 'success',
                'data' => $groupedData,
                'allData' => $ipData,
                'ruleIpCount' => $ruleIpCount,
                'ruleServerCount' => $ruleServerCount,
            ]);
        }
    }

    public function ip_manage_add()
    { 
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(200);
            exit;
        }

        $postData = json_decode(file_get_contents('php://input'), true);
        $serverAddr = !empty($postData['serverAddr']) ? $postData['serverAddr'] : ''; 
        $serverAddrOne = !empty($postData['serverAddrOne']) ? trim($postData['serverAddrOne']) : '';  

        $max_id = Db::table('AD_dns_ipRuleServer_api')->max('server_id');
        $serverId = $max_id + 1;

        $Server_addr = $this->dealWords($serverAddr);
        $Server_addr['-1'] = $serverAddrOne;  

        if (empty($Server_addr)) {
            return $this->ajaxReturn([
                'status' => 'error', 
                'message' => '上传IP不能为空!',
                'notIp' => [],
                'duplicateIp' => []
            ], 'json'); 
        }

        $Server_addr = array_filter($Server_addr); 

        $ipv4Pattern = '/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/';
        $ipv6Pattern = '/^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/';

        $notIp = [];
        $duplicateIp = [];
        $insertData = [];
        $time = time();

        $existingIps = Db::table('AD_dns_ipRuleServer_api')->column('server_addr');
        $existingIps = array_flip($existingIps);

        foreach ($Server_addr as $k => $ip) {
            if (!preg_match($ipv4Pattern, $ip) && !preg_match($ipv6Pattern, $ip)) {
                $notIp[] = $ip;
                break;
            }

            if (isset($existingIps[$ip])) {
                $duplicateIp[] = $ip;
                break;
            }

            $isMain = $k === -1 ? 2 : 0;

            $insertData[] = [
                'server_id' => $serverId,
                'is_main_addr' => $isMain,
                'server_addr' => $ip,
                'create_time' => $time,
                'update_time' => $time,
            ];
        }

        if (count($notIp) > 0 || count($duplicateIp) > 0) {
            return $this->ajaxReturn([
                'status' => 'error',
                'message' => '添加 IP 地址失败',
                'notIp' => $notIp,
                'duplicateIp' => $duplicateIp
            ], 'json');
        }

        if (!empty($insertData)) {
            $result = Db::table('AD_dns_ipRuleServer_api')->insertAll($insertData);

            if ($result) {
                return $this->ajaxReturn([
                    'status' => 'success',
                    'message' => 'IP 地址添加成功',
                    'notIp' => $notIp,
                    'duplicateIp' => $duplicateIp
                ], 'json');
            }
        }
    }

    protected function ajaxReturn($data, $type = '', $json_option = 0)
    {
        if (empty($type)) {
            $type = config('app.default_ajax_return');
        }

        switch (strtoupper($type)) {
            case 'JSON':
                header('Content-Type:application/json; charset=utf-8');
                $data = json_encode($data, $json_option);
                break;
            case 'JSONP':
                header('Content-Type:application/json; charset=utf-8');
                $handler = request()->get(config('app.var_jsonp_handler'), config('app.default_jsonp_handler'));
                $data = $handler . '(' . json_encode($data, $json_option) . ');';
                break;
            case 'EVAL':
                header('Content-Type:text/html; charset=utf-8');
                break;
        }
        exit($data);
    }

    // 继续重写其他方法，使用Db类替换数据库操作
}
